﻿using System;
using System.Collections.Generic;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Infra;
using Omu.ValueInjecter;

namespace Icms.Service
{
    public class ValsOnly : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            return c.SourceProp.Name == c.TargetProp.Name &&
                   c.SourceProp.Type == c.TargetProp.Type &&
                   !c.SourceProp.Type.IsSubclassOf(typeof(Entity));
        }

        protected override object SetValue(ConventionInfo c)
        {
            if (c.SourceProp.Type.IsGenericType && c.SourceProp.Type.GetGenericTypeDefinition() == typeof(ICollection<>))
            {
                if (c.SourceProp.Value == null) return null;

                dynamic repo = IoC.Resolve(typeof(IRepo<>).MakeGenericType(c.TargetProp.Type.GetGenericArguments()[0]));
                dynamic list = Activator.CreateInstance(typeof(List<>).MakeGenericType(c.TargetProp.Type.GetGenericArguments()[0]));

                foreach (var i in ((IEnumerable<Entity>)c.SourceProp.Value))
                    list.Add(repo.Get(i.Id));

                return list;
            }
            return base.SetValue(c);
        }
    }
}